package Util;

import entity.Manager;

import java.io.*;
import java.util.ArrayList;

/**
 * @Author: Tiangle
 * @Date: 2021/9/11 15:41
 */
public class FileIOUtil {
    private File file = new File("src\\save");
    public FileIOUtil(){
        if (!file.exists()){
            file.mkdir();
        }
    }

    public<E> ArrayList<E> input(String child){
        ArrayList<E> al = new ArrayList<>();
        File f = new File(file,child);
        if (!f.exists()){
            return al;
        }
        if (f.length()==0){
            return al;
        }
        ObjectInputStream ois =null;
        try {
            ois = new ObjectInputStream(new FileInputStream(f));
        }catch (IOException e) {
            e.printStackTrace();
        }

        try {
            al = (ArrayList<E>) ois.readObject();
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return al;
    }

    public<E> boolean output(String child,ArrayList<E> al){
        File f = new File(file,child);
        if (!f.exists()){
            try {
                f.createNewFile();
            } catch (IOException e) {
                return false;
            }
        }
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream(f));
        } catch (IOException e) {
            return false;
        }
        try {
            oos.writeObject(al);
            oos.close();
        } catch (IOException e) {
            return false;
        }

        return true;
    }


}
